package site.lanmushan.framework.datascope.interceptor.datascope;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import site.lanmushan.framework.datascope.bean.DataControlUserContext;
import site.lanmushan.framework.datascope.bus.DataScopeBus;
import site.lanmushan.framework.datascope.properties.DataScopeRule;
import site.lanmushan.framework.datascope.support.DataControlUserContextProvider;
import site.lanmushan.framework.datascope.support.DataScopeConditionProvider;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
public class AbstractDataScopeInterceptor {
    @Autowired
    private DataScopeConditionProvider dataScopeConditionProvider;
    @Autowired
    private DataControlUserContextProvider dataControlUserContextProvider;

     protected Expression getSelectDataScopeCondition(Map<String, String> tableMap, Map<String,List<DataScopeRule>> map,List<DataScopeRule> globalDataScopeRuleList) throws JSQLParserException {
        DataControlUserContext userContext = dataControlUserContextProvider.getUserContext();

        if (tableMap == null || tableMap.size() == 0) {
            return null;
        }
        List<String> conditionList = new ArrayList<>(tableMap.size());
        tableMap.forEach((key, value) -> {
            if (!DataScopeBus.isExcludeTable(key)) {
                if (DataScopeBus.isEnableTable(key)) {
                    String alias = value;
                    String condition = dataScopeConditionProvider.getCondition(key, userContext,map.get(key),globalDataScopeRuleList);
                    if (condition != null) {
                        condition = condition.replaceAll("#", alias + ".");
                        conditionList.add(condition);
                    }
                }
            }

        });
        if (conditionList.size() == 0) {
            return null;
        }
        List<String> whereList=conditionList.stream().distinct().collect(Collectors.toList());
        String fullCondition = String.join(" and ", whereList);
        return CCJSqlParserUtil.parseCondExpression("(" + fullCondition + ")");
    }
}
